package com.gem.back.common;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther:xzhang
 * @QQ:779774679
 * @Date:2020/3/2 09:04
 * @Description:
 */
public class StringToDate implements Converter<String, Date> {

    SimpleDateFormat sdf=new SimpleDateFormat();
    private List<String> patterns = new ArrayList<>();

    @Override
    public Date convert(String s) {
        patterns.add("yyyy-MM-dd HH:mm:ss");
        patterns.add("yyyy-MM-dd HH:mm");
        patterns.add("yyyy-MM-dd");
        patterns.add("HH:mm");
        patterns.add("yyyy-MM");
        Date date=null;
        for (String p : patterns) {
            try {
                sdf.applyPattern(p);
                date=sdf.parse(s);
                break;
            } catch (ParseException e) {}
        }
        if(date==null){
            throw new IllegalArgumentException("日期格式错误！[" + s + "]");
        }
        return date;
    }
    public void setPatterns(List<String> patterns) {
        this.patterns = patterns;
    }
}
